package lxy;

public class ThreadWorkt2 {
    public static void main(String[] args) {
        //设计4个线程，共享资源int类型的i,j； i与j初始值都为0；
        // 要求：两个线程每次对i和j增加1，另外两个线程对i和j每次减少1
        final ShareDate shareDate = new ShareDate();
        Thread t1 = new Thread(new T1(shareDate),"第一个加法线程：");
        Thread t2 = new Thread(new T1(shareDate),"第二个加法线程：");
        Thread t3 = new Thread(new T2(shareDate),"第三个减法线程：");
        Thread t4 = new Thread(new T2(shareDate),"第四个减法线程：");
        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }

    static class T1 implements Runnable{
        private ShareDate shareDate;

        public T1(ShareDate shareDate) {
            this.shareDate = shareDate;
        }

        @Override
        public void run() {
            shareDate.addDate();
        }
    }
    static class T2 implements Runnable{
        private ShareDate shareDate;

        public T2(ShareDate shareDate) {
            this.shareDate = shareDate;
        }

        @Override
        public void run() {
            shareDate.cutDate();
        }
    }

    static class ShareDate{
        int i = 0,j = 0;

        public synchronized void addDate(){
            i++;
            j++;
            System.out.println(Thread.currentThread().getName() + "i=" + i + "j=" + j);
        }

        public synchronized void cutDate(){
            i--;
            j--;
            System.out.println(Thread.currentThread().getName() + "i=" + i + "j=" + j);
        }
    }
}
